<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryFormRef"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="歌曲名" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入歌曲名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="歌手名 " prop="artistName">
        <el-input
          v-model="queryParams.artistName"
          placeholder="请输入所属歌手名 "
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属专辑名 " prop="albumName">
        <el-input
          v-model="queryParams.albumName"
          placeholder="请输入所属专辑名 "
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="时长" prop="duration">
        <el-input
          v-model="queryParams.duration"
          placeholder="请输入时长"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['music:music:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['music:music:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['music:music:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['music:music:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="musicList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="musicId" />
      <el-table-column label="歌曲名" align="center" prop="title" />
      <el-table-column label="歌手名 " align="center" prop="artistName" />
      <el-table-column label="所属专辑名 " align="center" prop="albumName" />
      <el-table-column label="时长" align="center" prop="duration" />
      <el-table-column label="歌曲文件" align="center" prop="fileUrl">
        <template #default="scope">
          <!-- 仅当 fileUrl 存在时才显示按钮 -->
          <el-button
            v-if="scope.row.fileUrl"
            size="mini"
            type="success"
            icon="CopyDocument"
            @click="handleCopy(scope.row.fileUrl)"
            >复制链接</el-button
          >
        </template>
      </el-table-column>
      <el-table-column label="歌词" align="center" prop="lyric" />
      <el-table-column label="创建者" align="center" prop="createBy" />
      <!-- 修改表格列的插槽语法 -->
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <!-- 将 slot-scope="scope" 修改为 #default="scope" -->
        <template #default="scope">
          <el-button
            size="mini"
            type="text"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['music:music:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['music:music:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改音乐作品对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="歌曲名" prop="title">
          <el-input v-model="form.title" placeholder="请输入歌曲名" />
        </el-form-item>
        <el-form-item label="所属歌手" prop="artistId">
          <el-select
            v-model="form.artistId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入歌手名搜索"
            :remote-method="remoteSearchArtist"
            :loading="artistLoading"
            style="width: 100%"
          >
            <el-option
              v-for="item in artistOptions"
              :key="item.artistId"
              :label="item.name"
              :value="item.artistId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属专辑" prop="albumId">
          <el-select
            v-model="form.albumId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入专辑名搜索"
            :remote-method="remoteSearchAlbum"
            :loading="albumLoading"
            style="width: 100%"
          >
            <el-option
              v-for="item in albumOptions"
              :key="item.albumId"
              :label="item.name"
              :value="item.albumId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时长(秒)" prop="duration">
          <el-input v-model="form.duration" placeholder="请输入时长(秒)" />
        </el-form-item>
        <el-form-item label="歌曲文件" prop="fileUrl">
          <file-upload
            v-model="form.fileUrl"
            :file-size="50"
            :file-type="['mp3', 'wav', 'flac']"
          />
        </el-form-item>
        <el-form-item label="歌词" prop="lyric">
          <el-input
            v-model="form.lyric"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <!-- 修改 footer 的插槽语法 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Music">
import {
  listMusic,
  getMusic,
  delMusic,
  addMusic,
  updateMusic,
} from "@/api/music/music";
import { selectArtist } from "@/api/music/artist";
import { selectAlbum } from "@/api/music/album";
import { CopyDocument } from "@element-plus/icons-vue";
/** 复制链接方法 */
function handleCopy(text) {
  if (!text) {
    proxy.$modal.msgError("链接为空，无法复制！");
    return;
  }
  // 使用浏览器的剪贴板 API
  navigator.clipboard
    .writeText(text)
    .then(() => {
      proxy.$modal.msgSuccess("链接已复制到剪贴板！");
    })
    .catch((err) => {
      console.error("复制失败:", err);
      proxy.$modal.msgError("复制失败，请稍后再试。");
    });
}
// 引入 Vue 3 的 ref, reactive, getCurrentInstance, nextTick
import { ref, reactive, toRefs, getCurrentInstance, nextTick } from "vue";

const { proxy } = getCurrentInstance();

// --- 数据状态 ---
// 使用 ref 或 reactive 来定义响应式数据
const musicList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const artistOptions = ref([]);
const artistLoading = ref(false);
const albumOptions = ref([]);
const albumLoading = ref(false);

// 使用 reactive 来组织表单和查询参数
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: undefined,
    artistName: undefined,
    albumName: undefined,
    duration: undefined,
  },
  rules: {
    title: [{ required: true, message: "歌曲名不能为空", trigger: "blur" }],
    artistId: [
      { required: true, message: "所属歌手ID不能为空", trigger: "blur" },
    ],
  },
});
const { queryParams, form, rules } = toRefs(data);

// --- 方法 ---

/** 查询音乐作品列表 */
function getList() {
  loading.value = true;
  listMusic(queryParams.value).then((response) => {
    musicList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    musicId: undefined,
    title: undefined,
    artistId: undefined,
    artistName: undefined,
    albumId: undefined,
    albumName: undefined,
    duration: undefined,
    fileUrl: undefined,
    lyric: undefined,
    status: undefined,
    remark: undefined,
  };
  proxy.resetForm("formRef"); // 注意 ref 的名字
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryFormRef"); // 注意 ref 的名字
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.musicId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加音乐作品";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const musicId = row.musicId || ids.value[0];
  getMusic(musicId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改音乐作品";
    // 回显歌手和专辑选项，防止编辑时选项为空
    if (form.value.artistName) {
      artistOptions.value = [
        { artistId: form.value.artistId, name: form.value.artistName },
      ];
    }
    if (form.value.albumName) {
      albumOptions.value = [
        { albumId: form.value.albumId, name: form.value.albumName },
      ];
    }
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["formRef"].validate((valid) => {
    // 注意 ref 的名字
    if (valid) {
      if (form.value.musicId != null) {
        updateMusic(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addMusic(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const musicIds = row.musicId || ids.value;
  proxy.$modal
    .confirm('是否确认删除音乐作品编号为"' + musicIds + '"的数据项？')
    .then(function () {
      return delMusic(musicIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "music/music/export",
    {
      ...queryParams.value,
    },
    `music_${new Date().getTime()}.xlsx`
  );
}

/** 远程搜索歌手列表 */
function remoteSearchArtist(query) {
  if (query) {
    artistLoading.value = true;
    selectArtist({ name: query }).then((response) => {
      artistOptions.value = response.rows;
      artistLoading.value = false;
    });
  } else {
    artistOptions.value = [];
  }
}

/** 远程搜索专辑列表 */
function remoteSearchAlbum(query) {
  if (query) {
    albumLoading.value = true;
    selectAlbum({ name: query }).then((response) => {
      albumOptions.value = response.rows;
      albumLoading.value = false;
    });
  } else {
    albumOptions.value = [];
  }
}

// --- 初始化 ---
getList();
</script>
